package com.ase.leetcode;

import java.util.*;

/**
 * @author gyhstart
 * @create 2021/3/14 - 11:42
 **/
public class Three {
    public static void main(String[] args) {
        int[][] array=new int[][]{
                {1,2,1},
                {2,3,3},
                {1,3,100},
        };
        System.out.println(beautifulPath(3, array, 1, 3));
    }

    static int beautifulPath(int n, int[][] edges, int start, int end) {
        Map<Integer, Map<Integer, Integer>> edgesMap = getEdgesMap(n, edges);
        int result = minPath(edgesMap, start, end);
        return result == Integer.MAX_VALUE ? -1 : result;
    }

    //构建图
    private static Map<Integer, Map<Integer, Integer>> getEdgesMap(int n, int[][] edges) {
        Map<Integer, Map<Integer, Integer>> map = new HashMap<>(2 * n);
        List<int[]> list = new ArrayList<>(n);
        Collections.addAll(list, edges);
        list.forEach(e -> {
            int start = e[0];
            int end = e[1];
            int distance = e[2];
            map.computeIfAbsent(start, k -> new HashMap<>(n));
            map.get(start).merge(end, distance, (a, b) -> b < a ? b : a);
        });
        return map;
    }

    //dfs求最小的路径
    private static int minPath(Map<Integer, Map<Integer, Integer>> edgesMap, int start, int end) {
        Map<Integer, Integer> startMap = edgesMap.get(start);
        int result = Integer.MAX_VALUE;
        for (Map.Entry<Integer, Integer> e : startMap.entrySet()) {
            int next = e.getKey();
            int path = e.getValue();
            if (next != end) {
                edgesMap.remove(start);
                path = path | minPath(edgesMap, next, end);
                edgesMap.put(start, startMap);
            }
            if (path < result) {
                result = path;
            }
        }
        return result;
    }
}
